package cn.sytton.taffecloud.serivce.auth.service.impl;

import cn.sytton.taffecloud.serivce.auth.captcha.CaptchaFactory;
import cn.sytton.taffecloud.serivce.auth.model.LoginModel;
import cn.sytton.taffecloud.serivce.auth.security.model.SecurityUser;
import cn.sytton.taffecloud.serivce.auth.service.ILoginService;
import cn.sytton.taffecloud.serivce.auth.security.sms.SmsCodeAuthenticationToken;
import cn.sytton.taffecloud.common.base.util.JwtUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 登录服务层实现类
 *
 * @author skyrock
 */
@Service
public class LoginService implements ILoginService {

    @Resource
    private CaptchaFactory captchaFactory;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private JwtUtil jwtUtil;

    @Override
    public String loginByPwd(LoginModel loginModel) {
        if (!captchaFactory.verifyCode(loginModel.getCaptchaId(), loginModel.getCaptchaCode())) {
            throw new BadCredentialsException("图片验证码错误或已过期");
        }
        Authentication authentication =  authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginModel.getLoginName(), loginModel.getPassword())
        );
        return generateToken(authentication);
    }

    @Override
    public String loginBySms(LoginModel loginModel) {
        Authentication authentication =  authenticationManager.authenticate(
                new SmsCodeAuthenticationToken(loginModel.getCellphone(), loginModel.getSmsCode())
        );
        return generateToken(authentication);
    }

    private String generateToken(Authentication authentication) {
        final SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        //生成token
        return jwtUtil.createToken(securityUser.getLoginUser());
    }
}
